package com.fnzn.entranceGuard.api;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.fnzn.entranceGuard.entity.power.*;
import com.fnzn.entranceGuard.entity.ths.ThsDay;
import com.fnzn.entranceGuard.entity.ths.ThsHour;
import com.fnzn.entranceGuard.rest.usrCloud.UsrApi;
import com.fnzn.entranceGuard.service.IGuardDeviceService;
import com.fnzn.entranceGuard.service.power.*;
import com.fnzn.entranceGuard.service.ths.IThsDayService;
import com.fnzn.entranceGuard.service.ths.IThsHourService;
import com.fnzn.entranceGuard.util.AjaxJson;
import com.fnzn.entranceGuard.util.DateTools;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.web.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author wf_sxf@163.com
 * @date 2019-01-03 9:08
 */
@Controller
@Slf4j
@RequestMapping("/api/power/")
public class PowerApi extends BaseController {
    @Autowired
    private IPowerDeviceService powerDeviceService;
    @Autowired
    private IPowerBaseService baseService;
    @Autowired
    private IPowerDayService dayService;
    @Autowired
    private IPowerHourService hourService;
    @Autowired
    private IPowerMonthService monthService;
    @Autowired
    private IGuardDeviceService deviceService;
    @Autowired
    private IThsDayService thsDayService;
    @Autowired
    private IThsHourService thsHourService;

    @GetMapping("listPowerDevices")
    @ResponseBody
    public AjaxJson listPowerDevices(Integer companyId) {
        AjaxJson json = new AjaxJson();
        json.setSuccess(true);
        try {
            List<PowerDevice> list = deviceService.getPowerDeviceByCompany(companyId);
            if (list == null || list.isEmpty()) {
                json.setMsg("您尚未安装模块");
                json.setSuccess(false);
                return json;
            }
            for(PowerDevice d : list) {
                if(UsrApi.getDevice(d.getDeviceId())) {
                    d.setOnline(true);
                }else{
                    d.setOnline(false);
                }
            }
            json.setObj(list);
        } catch (Exception e) {
            json.setSuccess(false);
            json.setMsg("获取模块列表异常，" + e.getMessage());
            log.error("获取模块列表异常，", e.getMessage());
        }
        return json;
    }

    @GetMapping("powerToday")
    @ResponseBody
    public AjaxJson powerToday(@RequestParam("deviceId") String deviceId,@RequestParam("powerId")String powerId) {
        AjaxJson json = new AjaxJson();
        json.setSuccess(true);
        Map<String, Object> result = new HashMap<>();
        try {
            PowerDevice device =  powerDeviceService.getPowerById(deviceId,powerId);
            if (device == null) {
                json.setMsg("您尚未安装此电表，如有疑问请联系管理员");
                json.setSuccess(false);
                return json;
            }
            /**
             * 本日数据
             */
            int year = DateTools.getCurrentYear();
            int month = DateTools.getCurrentMonth();
            int day = DateTools.getCurrentDay();
            Wrapper wrapper = new EntityWrapper<PowerDay>();
            wrapper.eq("year", year);
            wrapper.eq("month", month);
            wrapper.eq("day", day);
            wrapper.eq("device_id", device.getDeviceId());
            wrapper.eq("power_id", device.getPowerId());
            List<PowerDay> days = dayService.selectList(wrapper);
            if (days != null && !days.isEmpty()) {
                result.put("today", days.get(0));
            }
            /**
             * 本月用电
             */
            Wrapper wrapperMonth = new EntityWrapper<PowerMonth>();
            wrapperMonth.eq("year", year);
            wrapperMonth.eq("month", month);
            wrapperMonth.eq("device_id", device.getDeviceId());
            wrapperMonth.eq("power_id", device.getPowerId());
            List<PowerMonth> months = monthService.selectList(wrapperMonth);
            if (months != null && !months.isEmpty()) {
                result.put("month", months.get(0));
            }
            /**、
             * 昨日用电总量
             */
            String yesterDay = DateTools.getOldDay(-1);
            year = DateTools.getCurrentYearByDate(yesterDay);
            month = DateTools.getCurrentMonthByDate(yesterDay);
            day = DateTools.getCurrentDayByDate(yesterDay);
            wrapper = new EntityWrapper();
            wrapper.eq("year", year);
            wrapper.eq("month", month);
            wrapper.eq("day", day);
            wrapper.eq("device_id", device.getDeviceId());
            wrapper.eq("power_id", device.getPowerId());
            List<PowerDay> yearsterDays = dayService.selectList(wrapper);
            if (yearsterDays != null && !yearsterDays.isEmpty()) {
                result.put("yesterDay", yearsterDays.get(0));
            }
            /**
             * 上月平均 上月总量
             */
            String lastMonth = DateTools.getOldMonth(-1);
            year = DateTools.getCurrentYearByDate(lastMonth);
            month = DateTools.getCurrentMonthByDate(lastMonth);
            day = DateTools.getCurrentDayByDate(lastMonth);
            int dayNum = DateTools.getCurrentMonthLastDay(lastMonth);
            PowerMonth lastMonthPower = monthService.getByDeviceDate(device.getDeviceId(),year,month,device.getPowerId());
            if (lastMonthPower != null ) {
                result.put("lastMonthPower", lastMonthPower.getPower());
                result.put("lastMonthPowerAverage",lastMonthPower.getPower()==null ?0:lastMonthPower.getPower().divide(new BigDecimal(dayNum),2,BigDecimal.ROUND_HALF_UP));
            }

            /**
             * 异常
             * TODO
             */
            result.put("exception", 0);
            //运行时长
            Wrapper w = new EntityWrapper();
            w.eq("device_id", device.getDeviceId());
            w.eq("power_id", device.getPowerId());
            w.orderBy("create_time", true);
            w.last("limit 1");
            List<PowerBase> list = baseService.selectList(w);
            if (list != null && !list.isEmpty()) {
                result.put("runtime", DateTools.datePoorDiffMinute(list.get(0).getCreateTime(), new Date()));
            } else {
                result.put("runtime", 0);
            }
            json.setObj(result);
        } catch (Exception e) {
            json.setSuccess(false);
            json.setMsg("获取本日电费异常，" + e.getMessage());
            log.error("获取本日电费异常", e);
        }
        return json;
    }

    @GetMapping("powerDetail")
    @ResponseBody
    public AjaxJson powerDetail(@RequestParam("deviceId") String deviceId,@RequestParam("powerId")String powerId,
            @RequestParam(value = "date", required = true) String date, @RequestParam("type") String type) {
        AjaxJson json = new AjaxJson();
        Map<String, Object> result = new HashMap<>();
        json.setSuccess(true);
        try {
            PowerDevice device =  powerDeviceService.getPowerById(deviceId,powerId);
            if (device == null) {
                json.setMsg("您尚未安装此电表，如有疑问请联系管理员");
                json.setSuccess(false);
                return json;
            }
            String year = date.substring(0, 4);
            Integer month = Integer.parseInt(date.substring(4, 6));
            Wrapper wrapper = new EntityWrapper<PowerMonth>();
            wrapper.eq("device_id", device.getDeviceId());
            wrapper.eq("power_id", device.getPowerId());
            if (CommonConstant.POWER_TYPE_MONTH.equals(type)) {
                //按月返回数据
                wrapper.eq("year", year);
                List<PowerMonth> months = monthService.selectList(wrapper);
                result.put("months", months);
            } else if (CommonConstant.POWER_TYPE_DAY.equals(type)) {
                //查询本月详细信息
                wrapper.eq("year", year);
                wrapper.eq("month", month);
                result.put("days", dayService.selectList(wrapper));
            } else if (CommonConstant.POWER_TYPE_HOUR.equals(type)) {
                //查询本日详细信息
                wrapper.eq("date", date);
                result.put("hours", hourService.selectList(wrapper));
            }
            json.setObj(result);
        } catch (Exception e) {
            json.setSuccess(false);
            json.setMsg("获取电费详情错误，" + e.getMessage());
            log.error("获取电费详情错误", e);
        }
        return json;
    }

    @GetMapping("thsToday")
    @ResponseBody
    public AjaxJson thsToday(@RequestParam("deviceId") String deviceId,@RequestParam("powerId")String powerId) {
        AjaxJson json = new AjaxJson();
        json.setSuccess(true);
        Map<String, Object> result = new HashMap<>();
        try {
            PowerDevice device =  powerDeviceService.getPowerById(deviceId,powerId);
            if (device == null) {
                json.setMsg("您尚未安装此温湿度传感器，如有疑问请联系管理员");
                json.setSuccess(false);
                return json;
            }
            /**
             * 当前温湿度
             */
            Wrapper wrapper = new EntityWrapper<ThsHour>();
            wrapper.eq("date", DateTools.getCurrentSysData(DateTools.SIMPLE_FORMAT));
            wrapper.eq("device_id", device.getDeviceId());
            wrapper.eq("power_id", device.getPowerId());
            wrapper.orderBy("update_time",false);
            List<ThsHour> hours = thsHourService.selectList(wrapper);
            if (hours != null && !hours.isEmpty()) {
                result.put("today", hours.get(0));
            }
            json.setObj(result);
        } catch (Exception e) {
            json.setSuccess(false);
            json.setMsg("获取本日电费异常，" + e.getMessage());
            log.error("获取本日电费异常", e);
        }
        return json;
    }

    @GetMapping("thsDetail")
    @ResponseBody
    public AjaxJson thsDetail(@RequestParam("deviceId") String deviceId,@RequestParam("powerId")String powerId,
                                @RequestParam(value = "date", required = true) String date, @RequestParam("type") String type) {
        AjaxJson json = new AjaxJson();
        Map<String, Object> result = new HashMap<>();
        json.setSuccess(true);
        try {
            PowerDevice device =  powerDeviceService.getPowerById(deviceId,powerId);
            if (device == null) {
                json.setMsg("您尚未安装温湿度传感器，如有疑问请联系管理员");
                json.setSuccess(false);
                return json;
            }
            String year = date.substring(0, 4);
            Integer month = Integer.parseInt(date.substring(4, 6));
            Wrapper wrapper = new EntityWrapper<PowerMonth>();
            wrapper.eq("device_id", device.getDeviceId());
            wrapper.eq("power_id", device.getPowerId());
            if (CommonConstant.POWER_TYPE_DAY.equals(type)) {
                wrapper.eq("year", year);
                wrapper.eq("month", month);
                result.put("days", thsDayService.selectList(wrapper));
            } else if (CommonConstant.POWER_TYPE_HOUR.equals(type)) {
                wrapper.eq("date", date);
                result.put("hours", thsHourService.selectList(wrapper));
            }
            json.setObj(result);
        } catch (Exception e) {
            json.setSuccess(false);
            json.setMsg("获取温湿度详情错误，" + e.getMessage());
            log.error("获取温湿度详情错误", e);
        }
        return json;
    }
    public static void main(String[] args) {
        try {
            int days = DateTools.getCurrentMonthLastDay("20181102");
            System.out.println(days);

        } catch (Exception e) {

        }
    }


}
